﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Retrofit.Core
{
    public class ProcessManager : GameComponent
    {
        private List<Process> m_processList = new List<Process>();


        public ProcessManager(Game game)
            : base(game)
        {
        }

        public void Attach(Process process)
        {
            if (process != null)
            {
                m_processList.Add(process);
            }
        }

        public void Detach(Process process)
        {
            if (process != null)
            {
                if(m_processList.Contains(process))
                    m_processList.Remove(process);
            }
        }

        public bool HasProcesses
        {
            get { return m_processList.Count > 0; }
        }

        public override void Update(GameTime gameTime)
        {
            Process next;

            for (int i = 0; i < m_processList.Count; i++)
            {
                Process process = m_processList[i];

                if (process.IsDead)
                {
                    next = process.Next;

                    if (next != null)
                    {
                        process.Next = null;
                        Attach(next);
                    }
                    Detach(process);
                }
                else if (process.Active && !process.Paused)
                {
                    process.Update(gameTime);
                }
            }
            
            base.Update(gameTime);
        }

       
    }
}
